package de.nordakademie.wpk.share.ui.view.chartview;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map.Entry;

import de.nordakademie.wpk.share.core.data.Share;
import de.nordakademie.wpk.share.ui.Activator;

/**
 * @author Bent Juergensen
 *
 */
public class DataFetcher {
	private HashMap<GregorianCalendar, BigDecimal> dataMap;
	private ChartView cv;
	private int maxCourse;
	private int minCourse = 0;
	private Share sh;

	protected DataFetcher(ChartView cv, Share sh){
		this.cv = cv;
		this.sh = sh;
	}
	
	protected boolean initFetchData(){
		dataMap = Activator.getDefault().getShareService().getHistoricData(sh.getSymbol());
		cv.setDataMap(dataMap);
		// roughly check if data size is okay
		if(dataMap.size() <= 25){
			cv.setxValues(getXandYValueFromData(dataMap, true));
			cv.setyValues(getXandYValueFromData(dataMap, false));
			return true;
		}
		else
			return false;
	}
	
	private double[] getXandYValueFromData(HashMap<GregorianCalendar, BigDecimal> dataMap, boolean isXAxis){
		double[] db = new double[dataMap.size()];
		int i = dataMap.size()-1;
		for(Entry<GregorianCalendar, BigDecimal> e : dataMap.entrySet()){
		  BigDecimal b = e.getValue();
		  if (isXAxis)
			  db[i] = (double) i+1;
		  else{
			  db[i] = b.doubleValue();
			  if(minCourse == 0)
				  minCourse = b.intValue();
			  if(maxCourse < b.intValue()) // save max chart course to scale grid in chartview
				  maxCourse = b.intValue();
			  if(minCourse > b.intValue())
				  minCourse = b.intValue();
		  }
		  i--;
		}
		if(isXAxis)
			Arrays.sort(db);
		return db;	
	}
	
	protected int getMaxCourse() {
		return maxCourse;
	}

	protected int getMinCourse() {
		return minCourse;
	}
	
	protected void setMaxCourse(int maxCourse) {
		this.maxCourse = maxCourse;
	}

}
